//输入：root = [1, null, 2, 3]，输出：[1, 2, 3]

let root = {
    val: 1,
    left: null,
    right: {
        val: 2,
        left: 3
    }
}
var preorderTraversal = function (root) {
    if (!root) return []

    const res = []///创建栈
    const stack = []
    stack.push(root)//放root值进栈

    const cur = stack.pop()//cur是从栈顶拿出来的值

    res.push(cur.val)//将栈顶拿出来的值放进输出数组里，最后输出

    //循环判断，后序遍历：左右根
    while (stack.length) {

        if (cur.left) {
            stack.push(cur.left);
        }
        if (cur.right) {
            stack.push(cur.right);
        }

    }
    return res;//返回数组
};
console.log(preorderTraversal(root));
